package com.project.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan({"com.project.mapper","com.project.service"})
@MapperScan("com.project.mapper")
@EnableTransactionManagement
public class MybatisConfig {

    @Bean
    public DataSource getDate(){
        DruidDataSource dataSource=new DruidDataSource();
        //配置驱动
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        //配置url
        dataSource.setUrl("jdbc:mysql://localhost:12345/speakDB?characterEncoding=utf-8&;allowMultiQueries=true");
        //配置mysql登录名
        //
        dataSource.setUsername("root");
        //配置mysql密码
        dataSource.setPassword("lovo");
        //配置连接词的最大连接处
        dataSource.setMaxActive(100);
        //最小连接数
        dataSource.setMinIdle(20);
        //配置连接词超时时间
        dataSource.setMaxWait(1000);
        return  dataSource;
    }

    /**
     * 配置会话工厂
     * @return 工厂对象
     */
    @Bean
    public SqlSessionFactoryBean getFactoryBean(){
        SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
        //配置会化工厂数据源
        factoryBean.setDataSource(this.getDate());
        //读取配置文件
        factoryBean.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));
        return  factoryBean;
    }

    /**
     * 配置事务管理器
     * @return 事务管理器对象
     */
    @Bean
    public TransactionManager getTransaction(){
        DataSourceTransactionManager trans=new DataSourceTransactionManager();
        //设置事务管理器数据源
        trans.setDataSource(this.getDate());

        return trans;

    }
}
